<template>
  <van-pull-refresh
    class="atircleList"
    v-model="refreshing"
    :success-text="test"
    @refresh="onRefresh"
  >
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <Item v-for="(item, index) in list" :key="index" :item="item"></Item>
    </van-list>
  </van-pull-refresh>
</template>

<script>
import Item from '@/components/item.vue'
import { article } from '@/api/article.js'
export default {
  name: 'articleList',
  props: ['channel_id'],
  components: {
    Item
  },
  data () {
    return {
      list: [],
      timestamp: null,
      loading: false,
      error: false,
      finished: false,
      refreshing: false,
      test: ''
    }
  },
  methods: {
    // 初始加载和滑到最下面的时候触发
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const {
          data: {
            data
          }
        } = await article({
          channel_id: this.channel_id,
          timestamp: this.timestamp || Date.now()
        })
        this.timestamp = data.pre_timestamp
        this.list.push(...data.results)
      } catch (error) {
        this.error = true
      }
      // 加载状态结束
      this.loading = false
      // 数据全部加载完成
      if (!this.timestamp) {
        this.finished = true
      }
    },
    onRefresh () {
      setTimeout(async () => {
        try {
          const {
            data: {
              data: { results }
            }
          } = await article({
            channel_id: this.channel_id,
            timestamp: Date.now()
          })
          this.test = '刷新成功'
          this.list.unshift(...results)
        } catch (error) {
          this.test = '刷新失败'
        }
        this.refreshing = false
      }, 1000)
    }
  }
}
</script>

<style lang="less" scoped>
.atircleList {
  height: 78vh;
  overflow-y: auto;
}
</style>
